package com.study.agp.paging;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.study.agp.databinding.AdapterPagedItemBinding;
import java.util.Objects;

public class MoviePagedListAdapter extends PagedListAdapter<Movie, MoviePagedListAdapter.MovieViewHolder> {
    private final Context context;

    public MoviePagedListAdapter(Context context) {
        super(DIFF_CALL);
        this.context = context;
    }

    private static final DiffUtil.ItemCallback<Movie> DIFF_CALL = new DiffUtil.ItemCallback<Movie>() {
        @Override
        public boolean areItemsTheSame(@NonNull Movie oldItem, @NonNull Movie newItem) {
            return Objects.equals(oldItem.getTitle(), newItem.getTitle());
        }

        @Override
        public boolean areContentsTheSame(@NonNull Movie oldItem, @NonNull Movie newItem) {
            return Objects.equals(oldItem.getTitle(), newItem.getTitle());
        }
    };

    @NonNull
    @Override
    public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(this.context);
        AdapterPagedItemBinding binding = AdapterPagedItemBinding.inflate(inflater, parent, false);
        return new MovieViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MovieViewHolder holder, int position) {
        Movie movie = getItem(position);
        holder.binding.setMovie(movie);
    }

    public static class MovieViewHolder extends RecyclerView.ViewHolder {
        public final AdapterPagedItemBinding binding;
        public MovieViewHolder(@NonNull AdapterPagedItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
